package com.Controller;

import com.Service.CategoryService;
import com.Service.ProductService;
import com.pojo.Category;
import com.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/product")
public class ProductAdminController {
    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    public String list(Model model) {
        List<Product> products = productService.findAll();
        model.addAttribute("products", products);
        model.addAttribute("contentPage", "/admin/product/list.jsp");
        return "/admin/product/list";
    }

    @Autowired
    private CategoryService categoryService;
    @GetMapping("/add")
    public String addPage(Model model) {
        List<Category> categoryList = categoryService.findAll();
        model.addAttribute("categoryList", categoryList);
        return "/admin/product/add";
    }

    @PostMapping("/add")
    public String add(@ModelAttribute Product product) {
        productService.add(product);
        return "redirect:/admin/product/list";
    }


    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        Product product = productService.findById(id);
        List<Category> categoryList = categoryService.findAll();
        model.addAttribute("product", product);
        model.addAttribute("categoryList", categoryList);
        return "admin/product/edit";
    }

    @PostMapping("/edit")
    public String edit(@ModelAttribute Product product) {
        productService.update(product);
        return "redirect:/admin/product/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        try {
            productService.delete(id);
            redirectAttributes.addFlashAttribute("successMessage", "删除成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除失败：该拼团活动有关联数据，无法删除！");
        }
        return "redirect:/admin/product/list";
    }
}
